package com.sskjdata.cg.service.impl.auth;


import com.sskjdata.cg.jwt.JwtTokenUtil;
import com.sskjdata.cg.jwt.JwtUser;
import com.sskjdata.cg.service.auth.AuthService;
import com.sskjdata.cg.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

/**
 * @Descirption
 * @Author Jason
 * @Date 2019/11/28
 */
@Service
public class AuthServiceImpl extends BaseServiceImpl implements AuthService {

    @Autowired
    @Qualifier("jwtUserDetailsServiceImpl")
    private UserDetailsService userDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Override
    public String login(AuthenticationManager authenticationManager,String username, String password)throws Exception {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        String token = jwtTokenUtil.generateToken(userDetails);
        System.out.println("[生成token]："+token);
        return token;
    }

    @Override
    public String refresh(String oldToken) throws Exception{
        String username = jwtTokenUtil.getUsernameFromToken(oldToken);
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername(username);
        if (jwtTokenUtil.canTokenBeRefreshed(oldToken, user.getLastPasswordResetDate())){
            return jwtTokenUtil.refreshToken(oldToken);
        }
        return null;
    }
}
